/*
 * Copyright (c) 2019-2020, https://api.iot.10086.cn/(https://gitee.com/cmcc-iot-api/iot-card-open-application/).
 */
package cn.iot.card.open.ec.service;

import cn.iot.card.open.constants.Constants;
import cn.iot.card.open.constants.ErrorCode;
import cn.iot.card.open.constants.UrlConstants;
import cn.iot.card.open.ec.dto.ResponseDto;
import cn.iot.card.open.ec.dto.smartvoice.GroupSmartVoiceDTO;
import cn.iot.card.open.ec.dto.smartvoice.GroupVoiceDTO;
import cn.iot.card.open.ec.warpper.EcSmartVoiceWrapper;
import cn.iot.card.open.modular.model.ResultDTO;
import cn.iot.card.open.modular.token.TokenService;
import cn.iot.card.open.pojo.page.LayuiPageFactory;
import cn.iot.card.open.pojo.page.LayuiPageInfo;
import cn.iot.card.open.util.ApiRequestUtil;
import cn.iot.card.open.util.CommonUtil;
import cn.iot.card.open.util.JsonUtil;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.type.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 集团智能网语音信息查询业务操作
 *
 * @author cmcc-iot-api
 * @date 20191231 14:54:38
 */
@Service
@Slf4j
public class EcSmartVoiceService {

    @Autowired
    private ApiRequestUtil apiRequestUtil;

    @Autowired
    private TokenService tokenService;

    /**
     * 调用api接口根据条件查询集团智能网语音信息
     *
     * @param transId
     * @param accountId 集团id
     * @return
     * @throws IOException
     */
    public LayuiPageInfo selectEcSmartVoice(String transId, String accountId) throws IOException {
        Page page = LayuiPageFactory.defaultPage();
        if (StringUtils.isBlank(accountId)) {
            log.info("[{}] query EcSmartVoice error,accountId is null.", transId);
            return LayuiPageFactory.createEmptyPageInfo();
        }
        // 调用api接口：先获取token，然后带着token调用api接口
        ResultDTO tokenResultDTO = doRequestEcSmartVoice(true, accountId, transId, page);
        // 如果此处响应失败即为获取token失败，返回失败原因
        if (!tokenResultDTO.getCode().equals(ErrorCode.SUCCESS.getCode())) {
            ErrorCode errorCode = ErrorCode.getByCode(tokenResultDTO.getCode());
            return LayuiPageFactory.cteateErrorMsg(errorCode);
        }
        // 获取token成功后解析api接口的响应结果
        String responseStr = tokenResultDTO.getMsg();
        String code = CommonUtil.getApiRspCode(responseStr);
        // 获取api接口的响应结果状态码，如果状态码为12021（token不存在或已过期），则重新获取token后再次调用api接口
        if (ErrorCode.ERR12021.getCode().equals(code)) {
            log.warn("[{}] token[accountId:{}] of query EcSmartVoice is invalid and start to get a new token.", transId, accountId);
            tokenResultDTO = doRequestEcSmartVoice(false, accountId, transId, page);
            // 如果此处响应失败即为获取token失败，返回失败原因
            if (!tokenResultDTO.getCode().equals(ErrorCode.SUCCESS.getCode())) {
                ErrorCode errorCode = ErrorCode.getByCode(tokenResultDTO.getCode());
                return LayuiPageFactory.cteateErrorMsg(errorCode);
            }
            // 获取token成功后，重置responseStr（api接口的响应结果）
            responseStr = tokenResultDTO.getMsg();
        }
        log.info("[{}] query EcSmartVoice result string is {}.", transId, responseStr);
        // 组装页面信息
        ResponseDto<GroupSmartVoiceDTO> result = JsonUtil.parseJson(responseStr, new TypeReference<ResponseDto<GroupSmartVoiceDTO>>() {});
        code = result.getStatus();
        // 如果api接口返回失败，则返回失败原因
        if (!ErrorCode.SUCCESS.getCode().equals(code)) {
            log.warn("[{}] query EcSmartVoice error,error message is {}.", transId, result.getMessage());
            return LayuiPageFactory.cteateErrorMsg(ErrorCode.getByCode(code));
        }
        List<GroupSmartVoiceDTO> groupVoices = result.getResult();
        if (ToolUtil.isEmpty(groupVoices)) {
            log.warn("[{}] query EcSmartVoice end,result is null.", transId);
            return LayuiPageFactory.createEmptyPageInfo();
        }
        List<GroupVoiceDTO> groupVoiceDTOList = groupVoices.get(0).getGroupVoiceInfoList();
        String groupVoiceDTOListStr = JsonUtil.toJson(groupVoiceDTOList);
        List<Map<String,Object>> groupVoiceDTOMaps = JsonUtil.parseJson(groupVoiceDTOListStr, new TypeReference<List<Map<String,Object>>>(){});
        page.setTotal(groupVoiceDTOMaps.size());
        page.setRecords(groupVoiceDTOMaps);
        Page wrapped = new EcSmartVoiceWrapper(page).wrap();
        return LayuiPageFactory.createPageInfo(wrapped);
    }

    /**
     * 获取token，调用API接口
     *
     * @param tokenValid true表示使用已经初始化了的token值，false表示使用重新生成的token值
     * @param accountId 集团id
     * @param transId
     * @param page
     * @return 返回 API接口响应结果（或者获取token失败的原因）
     * @throws IOException
     * @author cmcc-iot-api
     * @date 20200107 09:16:37
     */
    private ResultDTO doRequestEcSmartVoice(boolean tokenValid, String accountId, String transId, Page page) throws IOException {
        // 根据 accountId 查询 token
        ResultDTO tokenResultDTO = tokenService.getToken(tokenValid, accountId);
        if (!tokenResultDTO.getCode().equals(ErrorCode.SUCCESS.getCode())) {
            return tokenResultDTO;
        }
        Map<String, String> parameterMap = new HashMap<>();
        parameterMap.put(Constants.REQUEST_PARAM_TOKEN, tokenResultDTO.getMsg());
        parameterMap.put(Constants.REQUEST_PARAM_TRANSID, transId);
        String startNum = String.valueOf(page.getCurrent());
        String pageSize = String.valueOf(page.getSize());
        parameterMap.put(Constants.REQUEST_PARAM_STARTNUM, startNum);
        parameterMap.put(Constants.REQUEST_PARAM_PAGESIZE, pageSize);
        String methodUrl = apiRequestUtil.buildRequestUrl(parameterMap, UrlConstants.QUERY_GROUP_SMART_VOICE);

        log.info("[{}] do request url is {}.", transId, methodUrl);

        tokenResultDTO.setMsg(apiRequestUtil.doGet(methodUrl));
        return tokenResultDTO;
    }

    /**
     * 获取企业客户成员通话参数列表.
     *
     * @param callParam 企业客户成员通话参数
     * @return 返回 call param list
     * @author cmcc-iot-api
     * @date 20200107 10:32:47
     */
    public Page<Map<String, Object>> getCallParamList(String callParam) {
        List<Map<String, String>> callParamList = JsonUtil.parseJson(callParam, new TypeReference<List<Map<String, String>>>(){});
        Page page = LayuiPageFactory.defaultPage();
        page.setTotal(callParamList.size());
        page.setRecords(callParamList);
        return page;
    }
}
